# -*- coding: utf-8 -*-
import re

from PyQt5 import QtCore
from PyQt5.QtWidgets import QMainWindow, QDialog

from global_data.glabal_data import GlobalData
from utils.dialog_utils import DialogUtils
from utils.icloudp_log import IcloudpLog
from windows.sys_config_edit import Ui_sys_config_win
import qtawesome as qta


class SysConfigEdit(object):
    def __init__(self, data=None, parent=None):
        self.parent = parent
        self.json_data = data
        self.sys_config_json = None
        self.ui = Ui_sys_config_win()
        self.win = QMainWindow()
        self.win.setWindowIcon(qta.icon(GlobalData.SYS_ICON))
        self.win.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)  # 置顶窗口
        self.init()
        self.init_data()

    def init(self):
        """
        主页面初始化
        :return:
        """
        try:
            self.ui.setupUi(self.win)

            self.win.setStyleSheet("""
                                .QWidget {border-width: 0px; border-style: none;}
                                .QStackedWidget {border-width: 0px; border-style: none;}
                                QFrame {border-width: 0; border-style: none;}
                                QGroupBox::title {line-height: 30px; margin-bottom: -10px; }
                                QLabel {font: 16px 宋体 ; color: #fff;}
                                QLineEdit {font: 16px 宋体 ; color: #fff;}
                                QPlainTextEdit {font: 16px 宋体 ; color: #fff; border-width: 1px; border-style: solid;}
                                QPushButton {font: 16px 宋体 ; color: #fff; height:25px; width:120px;}
                                QTextEdit {font: 16px 宋体 ; color: #fff; border-width: 1px; border-style: solid;}
                                QTextBrowser {font: 16px 宋体 ; color: #fff; }
                                QComboBox {font: 16px 宋体 ; color: #fff;}
                            """)
            # 绑定事件
            self.bind_events()
            # 绑定数据
            self.bind_data()
        except Exception as e:
            IcloudpLog.error(f"业务绑定错误: {e}")

    def show(self):
        self.win.show()

    def bind_data(self):
        self.ui.cb_sys_log_lev.addItem("信息", "info")
        self.ui.cb_sys_log_lev.addItem("警告", "warning")
        self.ui.cb_sys_log_lev.addItem("错误", "error")

        self.ui.cb_sys_cfg_load.addItem("开启", "1")
        self.ui.cb_sys_cfg_load.addItem("关闭", "0")
        self.ui.cb_sys_cfg_master.addItem("开启", True)
        self.ui.cb_sys_cfg_master.addItem("关闭", False)

        self.ui.cb_sys_remote_open.addItem("开启", True)
        self.ui.cb_sys_remote_open.addItem("关闭", False)

        self.ui.cb_sys_cache_open.addItem("开启", True)
        self.ui.cb_sys_cache_open.addItem("关闭", False)

        self.ui.cb_sys_temp_open.addItem("开启", "1")
        self.ui.cb_sys_temp_open.addItem("关闭", "0")

        self.ui.cb_sys_net_open.addItem("开启", "1")
        self.ui.cb_sys_net_open.addItem("关闭", "0")

        self.ui.cb_sys_smoke_open.addItem("开启", "1")
        self.ui.cb_sys_smoke_open.addItem("关闭", "0")

        self.ui.cb_sys_alerm_open.addItem("开启", "1")
        self.ui.cb_sys_alerm_open.addItem("关闭", "0")

        self.ui.cb_sys_relay_weight_open.addItem("开启", "1")
        self.ui.cb_sys_relay_weight_open.addItem("关闭", "0")

        self.ui.cb_sys_equip_open.addItem("开启", "1")
        self.ui.cb_sys_equip_open.addItem("关闭", "0")

        self.ui.cb_sys_send_temp_open.addItem("开启", "1")
        self.ui.cb_sys_send_temp_open.addItem("关闭", "0")

        self.ui.cb_sys_smoke_status_open.addItem("开启", "1")
        self.ui.cb_sys_smoke_status_open.addItem("关闭", "0")

        self.ui.cb_sys_spray_open.addItem("开启", "1")
        self.ui.cb_sys_spray_open.addItem("关闭", "0")

        self.ui.cb_sys_weight_open.addItem("开启", "1")
        self.ui.cb_sys_weight_open.addItem("关闭", "0")

        self.ui.cb_sys_equip_status_open.addItem("开启", "1")
        self.ui.cb_sys_equip_status_open.addItem("关闭", "0")

        self.ui.cb_sys_dts_relay_open.addItem("开启", "1")
        self.ui.cb_sys_dts_relay_open.addItem("关闭", "0")

        self.ui.cb_sys_wcs_open.addItem("开启", "1")
        self.ui.cb_sys_wcs_open.addItem("关闭", "0")

        self.ui.cb_sys_send_status_open.addItem("开启", "1")
        self.ui.cb_sys_send_status_open.addItem("关闭", "0")

    def init_data(self):
        """
        初始化数据
        :return:
        """
        if self.json_data is None:
            return
        try:
            self.__set_default_by_hidden_value(self.ui.cb_sys_log_lev, self.json_data["log"]["level"])
            self.ui.txt_sys_log_path.setText(self.json_data["log"]["path"])
            self.ui.txt_sys_log_count.setText(self.json_data["log"]["count"])

            self.__set_default_by_hidden_value(self.ui.cb_sys_remote_open,
                                               self.json_data["dtsSwapRestfulServer"]["enable"])
            self.ui.txt_sys_remote_ip.setText(self.json_data["dtsSwapRestfulServer"]["ip"])
            self.ui.txt_sys_remote_port.setText(self.json_data["dtsSwapRestfulServer"]["port"])

            self.ui.txt_sys_db_ip.setText(self.json_data["dbCfg"]["dbServer"]["host"])
            self.ui.txt_sys_db_port.setText(str(self.json_data["dbCfg"]["dbServer"]["port"]))
            self.ui.txt_sys_db_user.setText(self.json_data["dbCfg"]["dbServer"]["user"])
            self.ui.txt_sys_db_pwd.setText(self.json_data["dbCfg"]["dbServer"]["password"])
            self.ui.txt_sys_db_name.setText(self.json_data["dbCfg"]["dbServer"]["database"])

            self.__set_default_by_hidden_value(self.ui.cb_sys_cfg_load,
                                               self.json_data["sysCfg"]["isLoadCfg"])
            self.ui.txt_sys_cfg_path.setText(self.json_data["sysCfg"]["loadCfgPath"])
            self.ui.txt_sys_cfg_time.setText(str(self.json_data["sysCfg"]["stableWaitTime"]))

            self.__set_default_by_hidden_value(self.ui.cb_sys_cfg_master,
                                               self.json_data["isMaster"])
            self.ui.txt_sys_cfg_id.setText(str(self.json_data["id"]))

            self.__set_default_by_hidden_value(self.ui.cb_sys_cache_open,
                                               self.json_data["sysCfg"]["printBuffer"]["enable"])
            self.ui.txt_sys_cache_time.setText(str(self.json_data["sysCfg"]["printBuffer"]["interval"]))

            self.ui.txt_sys_relay_port.setText(self.json_data["sysCfg"]["relay"]["port"])
            self.ui.txt_sys_relay_position.setText(
                str(self.json_data["sysCfg"]["relay"]["start"]) + "," + str(self.json_data["sysCfg"]["relay"]["end"]))

            self.__set_default_by_hidden_value(self.ui.cb_sys_temp_open,
                                               self.json_data["threadCfg"]["dtsClientThread"]["isOpen"])
            self.ui.txt_sys_temp_time.setText(str(self.json_data["threadCfg"]["dtsClientThread"]["interval"]))

            self.__set_default_by_hidden_value(self.ui.cb_sys_net_open,
                                               self.json_data["threadCfg"]["recTcpClientThread"]["isOpen"])
            self.ui.txt_sys_net_time.setText(str(self.json_data["threadCfg"]["recTcpClientThread"]["interval"]))

            self.__set_default_by_hidden_value(self.ui.cb_sys_smoke_open,
                                               self.json_data["threadCfg"]["gbAlarmServerThread"]["isOpen"])
            self.ui.txt_sys_smoke_time.setText(str(self.json_data["threadCfg"]["gbAlarmServerThread"]["interval"]))

            self.__set_default_by_hidden_value(self.ui.cb_sys_alerm_open,
                                               self.json_data["threadCfg"]["alarmSendThread"]["isOpen"])
            self.ui.txt_sys_alerm_cmd_dts.setText(self.json_data["threadCfg"]["alarmSendThread"]["server"]["dtsCmd"])

            self.__set_default_by_hidden_value(self.ui.cb_sys_relay_weight_open,
                                               self.json_data["threadCfg"]["relayRecordThread"]["isOpen"])

            self.__set_default_by_hidden_value(self.ui.cb_sys_equip_open,
                                               self.json_data["threadCfg"]["faultSendThread"]["isOpen"])
            fault_send_thread = self.json_data["threadCfg"]["faultSendThread"]["typeList"]
            for item in fault_send_thread:
                if "fiber" == item:
                    self.ui.ck_sys_equip_fiber.setChecked(True)

            self.__set_default_by_hidden_value(self.ui.cb_sys_send_temp_open,
                                               self.json_data["threadCfg"]["temperatureSendThread"]["isOpen"])

            self.__set_default_by_hidden_value(self.ui.cb_sys_smoke_status_open,
                                               self.json_data["threadCfg"]["gbAlarmSendThread"]["isOpen"])

            self.__set_default_by_hidden_value(self.ui.cb_sys_spray_open,
                                               self.json_data["threadCfg"]["neotecSendThread"]["isOpen"])

            self.__set_default_by_hidden_value(self.ui.cb_sys_weight_open,
                                               self.json_data["threadCfg"]["alarmWeightSwapThread"]["isOpen"])

            self.__set_default_by_hidden_value(self.ui.cb_sys_equip_status_open,
                                               self.json_data["threadCfg"]["statetSwapThread"]["isOpen"])

            self.__set_default_by_hidden_value(self.ui.cb_sys_dts_relay_open,
                                               self.json_data["threadCfg"]["dtsAlarmThread"]["isOpen"])

            self.__set_default_by_hidden_value(self.ui.cb_sys_wcs_open,
                                               self.json_data["threadCfg"]["wcsAlarmSendThread"]["isOpen"])
            self.ui.txt_sys_wcs_time.setText(
                str(self.json_data["threadCfg"]["wcsAlarmSendThread"]["server"]["sendSleep"]))
            self.ui.txt_sys_wcs_version.setText(
                self.json_data["threadCfg"]["wcsAlarmSendThread"]["server"]["wcsverion"])

            self.__set_default_by_hidden_value(self.ui.cb_sys_send_status_open,
                                               self.json_data["threadCfg"]["pubDataSendThread"]["isOpen"])
            pub_data_send_thread = self.json_data["threadCfg"]["pubDataSendThread"]["typeList"]
            for item in pub_data_send_thread:
                if "modbus" == item:
                    self.ui.ck_sys_send_modbus.setChecked(True)
                if "wcs" == item:
                    self.ui.ck_sys_send_wcs.setChecked(True)
                if "state" == item:
                    self.ui.ck_sys_send_state.setChecked(True)
        except Exception as e:
            IcloudpLog.error(f"初始数据错误: {e}")

    def __set_default_by_hidden_value(self, cb, hidden_value):
        for i in range(cb.count()):
            if cb.itemData(i) == hidden_value:
                cb.setCurrentIndex(i)
                break

    def bind_events(self):
        self.ui.btn_save.clicked.connect(self.save_data)
        # self.ui.cb_sys_log_lev.currentIndexChanged.connect(self.cb_sys_log_lev_change)
        # self.ui.cb_sys_log_lev.activated.connect(self.cb_sys_log_lev_active)

    def cb_sys_log_lev_change(self, index):
        """
        日志级别变化事件
        :param index:
        :return:
        """
        # 获取当前选中项的隐藏值
        hidden_value = self.ui.cb_sys_log_lev.itemData(index)

    def save_data(self):
        """
        提交保存数据
        :return:
        """
        try:
            self.get_data()
            self.parent.set_page_txt(self.json_data, 0)
            self.win.close()
            DialogUtils.msg("结果已输出到页面文本框，请复制粘贴或者导出到文件保存！")
            # self.parent.sys_config_dialog_win.close()
        except Exception as e:
            IcloudpLog.error(f"保存数据错误: {e}")

    def get_data(self):
        """
        从页面获取数据
        :return:
        """
        try:
            cfg_log = self.json_data["log"]
            cfg_log["level"] = self.ui.cb_sys_log_lev.itemData(self.ui.cb_sys_log_lev.currentIndex())
            cfg_log["path"] = self.ui.txt_sys_log_path.text()
            cfg_log["count"] = self.ui.txt_sys_log_count.text()
            self.json_data["log"] = cfg_log

            cfg_remote = self.json_data["dtsSwapRestfulServer"]
            cfg_remote["ip"] = self.ui.txt_sys_remote_ip.text()
            cfg_remote["port"] = self.ui.txt_sys_remote_port.text()
            cfg_remote["enable"] = self.ui.cb_sys_remote_open.itemData(self.ui.cb_sys_remote_open.currentIndex())
            self.json_data["dtsSwapRestfulServer"] = cfg_remote

            cfg_db = self.json_data["dbCfg"]["dbServer"]
            cfg_db["host"] = self.ui.txt_sys_db_ip.text()
            cfg_db["port"] = self.ui.txt_sys_db_port.text()
            cfg_db["user"] = self.ui.txt_sys_db_user.text()
            cfg_db["password"] = self.ui.txt_sys_db_pwd.text()
            cfg_db["database"] = self.ui.txt_sys_db_name.text()
            self.json_data["dbCfg"]["dbServer"] = cfg_db

            cfg_sys = self.json_data["sysCfg"]
            cfg_sys["isLoadCfg"] = self.ui.cb_sys_cfg_load.itemData(self.ui.cb_sys_cfg_load.currentIndex())
            cfg_sys["loadCfgPath"] = self.ui.txt_sys_log_path.text()
            cfg_sys["stableWaitTime"] = self.ui.txt_sys_cfg_time.text()
            cfg_sys["printBuffer"]["enable"] = self.ui.cb_sys_cache_open.itemData(
                self.ui.cb_sys_cache_open.currentIndex())
            cfg_sys["printBuffer"]["interval"] = self.ui.txt_sys_cache_time.text()
            cfg_sys["relay"]["port"] = self.ui.txt_sys_relay_port.text()
            relay_pos = self.ui.txt_sys_relay_position.text()
            if relay_pos:
                res1 = re.split(r'[, ，_-]', relay_pos)
                if len(res1) > 1:
                    cfg_sys["relay"]["start"] = res1[0]
                    cfg_sys["relay"]["end"] = res1[1]
                else:
                    cfg_sys["relay"]["start"] = res1[0]

            self.json_data["isMaster"] = self.ui.cb_sys_cfg_master.itemData(self.ui.cb_sys_cfg_master.currentIndex())
            self.json_data["id"] = self.ui.txt_sys_cfg_id.text()

            cfg_temp = self.json_data["threadCfg"]["dtsClientThread"]
            cfg_temp["isOpen"] = self.ui.cb_sys_temp_open.itemData(self.ui.cb_sys_temp_open.currentIndex())
            cfg_temp["interval"] = self.ui.txt_sys_temp_time.text()
            self.json_data["threadCfg"]["dtsClientThread"] = cfg_temp

            cfg_net = self.json_data["threadCfg"]["recTcpClientThread"]
            cfg_net["isOpen"] = self.ui.cb_sys_net_open.itemData(self.ui.cb_sys_net_open.currentIndex())
            cfg_net["interval"] = self.ui.txt_sys_net_time.text()
            self.json_data["threadCfg"]["recTcpClientThread"] = cfg_net

            cfg_smoke = self.json_data["threadCfg"]["gbAlarmServerThread"]
            cfg_smoke["isOpen"] = self.ui.cb_sys_smoke_open.itemData(self.ui.cb_sys_smoke_open.currentIndex())
            cfg_smoke["interval"] = self.ui.txt_sys_smoke_time.text()
            self.json_data["threadCfg"]["gbAlarmServerThread"] = cfg_smoke

            cfg_alerm = self.json_data["threadCfg"]["alarmSendThread"]
            cfg_alerm["isOpen"] = self.ui.cb_sys_alerm_open.itemData(self.ui.cb_sys_alerm_open.currentIndex())
            cfg_alerm["interval"] = self.ui.txt_sys_alerm_cmd_dts.text()
            self.json_data["threadCfg"]["alarmSendThread"] = cfg_alerm

            cfg_relay_weight = self.json_data["threadCfg"]["relayRecordThread"]
            cfg_relay_weight["isOpen"] = self.ui.cb_sys_relay_weight_open.itemData(
                self.ui.cb_sys_relay_weight_open.currentIndex())
            self.json_data["threadCfg"]["relayRecordThread"] = cfg_relay_weight

            cfg_equip = self.json_data["threadCfg"]["faultSendThread"]
            cfg_equip["isOpen"] = self.ui.cb_sys_equip_open.itemData(self.ui.cb_sys_equip_open.currentIndex())
            # 增加列表
            cfg_equip_list = []
            if self.ui.ck_sys_equip_fiber.isChecked():
                cfg_equip_list.append("fiber")
            cfg_equip["typeList"] = cfg_equip_list
            self.json_data["threadCfg"]["faultSendThread"] = cfg_equip

            cfg_send_temp = self.json_data["threadCfg"]["temperatureSendThread"]
            cfg_send_temp["isOpen"] = self.ui.cb_sys_send_temp_open.itemData(
                self.ui.cb_sys_send_temp_open.currentIndex())
            self.json_data["threadCfg"]["temperatureSendThread"] = cfg_send_temp

            cfg_smoke_status = self.json_data["threadCfg"]["gbAlarmSendThread"]
            cfg_smoke_status["isOpen"] = self.ui.cb_sys_smoke_status_open.itemData(
                self.ui.cb_sys_smoke_status_open.currentIndex())
            self.json_data["threadCfg"]["gbAlarmSendThread"] = cfg_smoke_status

            cfg_spray = self.json_data["threadCfg"]["neotecSendThread"]
            cfg_spray["isOpen"] = self.ui.cb_sys_spray_open.itemData(self.ui.cb_sys_spray_open.currentIndex())
            self.json_data["threadCfg"]["neotecSendThread"] = cfg_spray

            cfg_weight = self.json_data["threadCfg"]["alarmWeightSwapThread"]
            cfg_weight["isOpen"] = self.ui.cb_sys_weight_open.itemData(self.ui.cb_sys_weight_open.currentIndex())
            self.json_data["threadCfg"]["alarmWeightSwapThread"] = cfg_weight

            cfg_equip_status = self.json_data["threadCfg"]["statetSwapThread"]
            cfg_equip_status["isOpen"] = self.ui.cb_sys_equip_status_open.itemData(
                self.ui.cb_sys_equip_status_open.currentIndex())
            self.json_data["threadCfg"]["statetSwapThread"] = cfg_equip_status

            cfg_dts_relay = self.json_data["threadCfg"]["dtsAlarmThread"]
            cfg_dts_relay["isOpen"] = self.ui.cb_sys_dts_relay_open.itemData(
                self.ui.cb_sys_dts_relay_open.currentIndex())
            self.json_data["threadCfg"]["dtsAlarmThread"] = cfg_dts_relay

            cfg_wcs = self.json_data["threadCfg"]["wcsAlarmSendThread"]
            cfg_wcs["isOpen"] = self.ui.cb_sys_wcs_open.itemData(self.ui.cb_sys_wcs_open.currentIndex())
            cfg_wcs["server"]["sendSleep"] = self.ui.txt_sys_wcs_time.text()
            cfg_wcs["server"]["wcsverion"] = self.ui.txt_sys_wcs_version.text()
            self.json_data["threadCfg"]["wcsAlarmSendThread"] = cfg_wcs

            cfg_send_status = self.json_data["threadCfg"]["pubDataSendThread"]
            cfg_send_status["isOpen"] = self.ui.cb_sys_send_status_open.itemData(
                self.ui.cb_sys_send_status_open.currentIndex())
            # 增加列表
            cfg_send_status_list = []
            if self.ui.ck_sys_send_wcs.isChecked():
                cfg_send_status_list.append("wcs")
            if self.ui.ck_sys_send_modbus.isChecked():
                cfg_send_status_list.append("modbus")
            if self.ui.ck_sys_send_state.isChecked():
                cfg_send_status_list.append("state")
            cfg_send_status["typeList"] = cfg_send_status_list
            self.json_data["threadCfg"]["pubDataSendThread"] = cfg_send_status


        except Exception as e:
            IcloudpLog.error(f"获取页面数据，绑定错误: {e}")


if __name__ == '__main__':
    print("Python")
